package com.teng.smartdrawer;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.teng.smartdrawer.bean.RefreshEvent;
import com.teng.smartdrawer.bean.User;
import com.teng.smartdrawer.parser.DataConstants;
import com.teng.smartdrawer.parser.DataParser;
import com.teng.smartdrawer.utils.CustomDialog;
import com.teng.smartdrawer.utils.PreferenceUtils;

import de.greenrobot.event.EventBus;


public class LoginActivity extends AppCompatActivity implements View.OnClickListener {

    TextView tv_login ;
    EditText et_pwd , et_number;
    private boolean isFromWelcome;
    private PreferenceUtils preferenceUtils;
    public static ImageView useraccount_headimg,userpassword_headimg,userpassword_delete,useraccount_delete,head_share;
    private Dialog progressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        isFromWelcome = getIntent().getBooleanExtra("isFromWelcome", false);

        progressDialog = CustomDialog.createLoadingDialog(this, "正在登陆...");

        tv_login = (TextView) findViewById(R.id.tv_login);
        tv_login.setOnClickListener(this);

        et_pwd = (EditText) findViewById(R.id.et_pwd);
        et_pwd.addTextChangedListener(new PasswordEditChangeListener());

        et_number = (EditText) findViewById(R.id.et_number);
        et_number.addTextChangedListener(new UserEditChangeListener());

        ImageView exit_window = (ImageView) findViewById(R.id.exit_window);
        exit_window.setOnClickListener(this);

        preferenceUtils = PreferenceUtils.getInstance(this);
        initUI();
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // TODO actionBar返回处理
        if(item.getItemId() == android.R.id.home)
        {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.tv_login:
                // TODO 登录
                String account = et_number.getText().toString();
                String psw = et_pwd.getText().toString();

                if (account == null || "".equals(account) || psw == null || "".equals(psw)) {
                    Toast.makeText(LoginActivity.this, "账号或密码不能为空", Toast.LENGTH_SHORT).show();
                }else {
                    DataParser.getLoginResult(LoginActivity.this, handler, account, psw);
                    progressDialog.show();
                }

                break;
            case R.id.actionbar_back:

                if (isFromWelcome)
                    goMainActivity();
                else
                    finish();

                break;
            case R.id.exit_window:

                finish();
                break;
            case R.id.userpassword_delete:
                et_pwd.setText("");
                break;
            case R.id.useraccount_delete:
                et_number.setText("");
                break;
            default:

                break;
        }
    }

    Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {

            switch (msg.what){
                case DataConstants.LOGIN_SIGN:

                    User user = (User) msg.obj;
                    progressDialog.dismiss();
                    if (user.getStatus() == 200){
                       // TODO 登录成功
                        preferenceUtils.addString(PreferenceUtils.USER_NAME , user.getA_truename());
                        preferenceUtils.addString(PreferenceUtils.USER_ACCOUNT_NUMBER , user.getA_account());
                        preferenceUtils.addString(PreferenceUtils.USER_HEAD_PIC , user.getA_headimage());
                        preferenceUtils.addString(PreferenceUtils.USER_AUTHORITY, user.getA_authority());
                        preferenceUtils.addBoolean(PreferenceUtils.USER_IS_LOGIN, true);
                        MyApplication.isLogin = true;
                        Toast.makeText(LoginActivity.this , "登录成功" , Toast.LENGTH_SHORT).show();
                        //setResult(RESULT_OK);

                        EventBus.getDefault().post(
                                new RefreshEvent(true));

                        finish();
                    }else if (user.getStatus() == 403){

                        Toast.makeText(LoginActivity.this , "密码错误" , Toast.LENGTH_SHORT).show();

                    }else if (user.getStatus() == 404){

                        Toast.makeText(LoginActivity.this , "账号错误" , Toast.LENGTH_SHORT).show();

                    }else {

                        Toast.makeText(LoginActivity.this , "请检查账号密码" , Toast.LENGTH_SHORT).show();

                    }

                    break;
                default:
                    break;
            }

            return false;
        }
    });


    private void goMainActivity(){
        Intent intent = new Intent(this , MainActivity.class);
        startActivity(intent);
        finish();
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        if (isFromWelcome)
            goMainActivity();
        else
            finish();
    }

    /**
     * UI初始化
     */
    public void initUI(){
        useraccount_delete = (ImageView) findViewById(R.id.useraccount_delete);
        userpassword_delete = (ImageView) findViewById(R.id.userpassword_delete);
        useraccount_headimg = (ImageView) findViewById(R.id.useraccount_headimg);
        userpassword_headimg = (ImageView) findViewById(R.id.userpassword_headimg);

        userpassword_delete.setOnClickListener(this);
        useraccount_delete.setOnClickListener(this);
    }
    /**
     *
     * 设置Edittext输入监听
     * @author wangteng
     *
     */
    class UserEditChangeListener implements TextWatcher{
        CharSequence temp;
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {
            useraccount_headimg.setBackgroundResource(R.mipmap.login_user);
            useraccount_delete.setVisibility(View.INVISIBLE);
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            temp = s;
        }

        @Override
        public void afterTextChanged(Editable s) {
            if(temp.length()>0){
                useraccount_headimg.setBackgroundResource(R.mipmap.login_user_hightlighted);
                useraccount_delete.setVisibility(View.VISIBLE);
            }
        }

    }
    class PasswordEditChangeListener implements TextWatcher{
        CharSequence temp;
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {
            userpassword_headimg.setBackgroundResource(R.mipmap.login_key);
            userpassword_delete.setVisibility(View.INVISIBLE);
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            temp = s;
        }

        @Override
        public void afterTextChanged(Editable s) {
            if(temp.length()>0){
                userpassword_headimg.setBackgroundResource(R.mipmap.login_key_hightlighted);
                userpassword_delete.setVisibility(View.VISIBLE);
            }
        }
    }
}
